//
//  KLBuyViewController.m
//  used
//
//  Created by xalo on 16/7/15.
//  Copyright © 2016年 王凯. All rights reserved.
//

#import "KLBuyViewController.h"
#import "LrdSuperMenu.h"

@interface KLBuyViewController ()<LrdSuperMenuDataSource, LrdSuperMenuDelegate, KLSelectedViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, KLSelectedViewControllerDelegate>;


@property (nonatomic, strong) UICollectionView *collectionView;
/** searchBar */
@property (nonatomic, strong) UISearchBar *searchBar;
/** 分类 */
@property (nonatomic, strong) NSMutableArray *cates;
/** 子分类 */
@property (nonatomic, strong) NSMutableArray *subCates;
/** 城市列表 */
@property (nonatomic, strong) NSMutableArray *citys;
/** 省列表 */
@property (nonatomic, strong) NSMutableArray *provinces;
/** 菜单 */
@property (nonatomic, strong) LrdSuperMenu *menu;
/** 排序子菜单 */
@property (nonatomic, strong) NSArray *sorts;
/** 删选子菜单 */
@property (nonatomic, strong) KLSelectedView *selectedView;
/** 物品列表 */
@property (nonatomic, strong) NSMutableArray *goods;


@property (nonatomic, strong) UICollectionViewFlowLayout *twoViewLayout;
@property (nonatomic, strong) UICollectionViewFlowLayout *oneViewLayout;
@property (nonatomic, assign) BOOL isChanged;
@property (nonatomic, strong) UIButton *lastPriceLabel;
/** page */
@property (nonatomic, assign) NSInteger page;

@property (strong, nonatomic) FeHourGlass *hourGlass;


@property (nonatomic, strong) NSMutableDictionary *lastPara;

@end

@implementation KLBuyViewController


#pragma mark - 懒加载

- (NSMutableDictionary *)lastPara {
    if (!_lastPara) {
        _lastPara = [NSMutableDictionary dictionary];
    }
    return _lastPara;
}

- (NSMutableArray *)goods {
    if (!_goods) {
        _goods = [NSMutableArray array];
    }
    return _goods;
}

- (UICollectionViewFlowLayout *)twoViewLayout {
    if (!_twoViewLayout) {
        _twoViewLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemW = (kWidth - 30) / 2;
        CGFloat itemH = itemW * 1.6;
        _twoViewLayout.itemSize = CGSizeMake(itemW, itemH);
        _twoViewLayout.minimumInteritemSpacing = 10;
        _twoViewLayout.minimumLineSpacing = 10;
        _twoViewLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    }
    return _twoViewLayout;
}

- (UICollectionViewFlowLayout *)oneViewLayout {
    if (!_oneViewLayout) {
        _oneViewLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemW = kWidth - 20;
        CGFloat itemH = itemW * 0.4;
        _oneViewLayout.itemSize = CGSizeMake(itemW, itemH);
        _oneViewLayout.minimumInteritemSpacing = 10;
        _oneViewLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    }
    return _oneViewLayout;
}

- (NSMutableArray *)cates {
    if (!_cates) {
        _cates = [NSMutableArray array];
    }
    return _cates;
}

- (NSMutableArray *)subCates {
    if (!_subCates) {
        _subCates = [NSMutableArray array];
    }
    return _subCates;
}

- (KLSelectedView *)selectedView {
    if (!_selectedView) {
        _selectedView = [KLSelectedView selectedView];
        _selectedView.frame = CGRectMake(0, 44 - kHeight * 0.4, kWidth, kHeight * 0.4);
        _selectedView.delegate = self;
    }
    return _selectedView;
}

- (LrdSuperMenu *)menu {
    if (!_menu) {
        _menu = [[LrdSuperMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];

        _menu.dataSource = self;
        _menu.delegate = self;
    }
    return _menu;
}


- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.placeholder = @"请输入宝贝关键字或 @卖家名";
        _searchBar.delegate = self;        
    }
    return _searchBar;
}


#pragma mark - 加载视图

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    // 设置导航栏
    [self setupNavigation];
    // 添加collectionView
    [self addCollectionView];
    // 添加菜单视图
    [self.view addSubview:self.menu];
    //  获取菜单数据
    [self getMenuData];
    // 设置菜单标题
    [self setMenuTitle];
    // 请求分类数据
    [self loadCateData];
    // 请求物品数据

    // 添加刷新功能
    [self setupRefresh];
    if(!self.parameters) {
        [self loadGoodsDataWithParameters:@{@"page":@0}];
        [self.collectionView.mj_header beginRefreshing];
    }

    self.hourGlass = [[FeHourGlass alloc] initWithView:self.view];
    [self.view addSubview:self.hourGlass];
    [self.hourGlass show];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    NSLog(@"%@------%@", self.parameters, self.lastPara);
    if(self.parameters != self.lastPara) {
        [self loadGoodsDataWithParameters:self.parameters];
        [self.collectionView.mj_header beginRefreshing];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.searchBar.text = nil;
    self.lastPara = self.parameters;
    [self.hourGlass dismiss];
}


- (void)setMenuTitle {
    
    [self.menu selectIndexPath:[LrdIndexPath indexPathWithColumn:0 row:0]];
    [self.menu selectIndexPath:[LrdIndexPath indexPathWithColumn:1 row:0]];
    [self.menu selectIndexPath:[LrdIndexPath indexPathWithColumn:2 row:0]];

}

- (void)addCollectionView {
    
   self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44, kWidth, kHeight - 44) collectionViewLayout:self.twoViewLayout];
    self.collectionView.backgroundColor = KLRGBColor(240, 240, 240);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerNib:[UINib nibWithNibName:@"KLGoodsCell" bundle:nil] forCellWithReuseIdentifier:@"goodsCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"KLGoodsOtherCell" bundle:nil] forCellWithReuseIdentifier:@"otherGoods"];
}

#pragma mark - 请求数据
// 添加刷新功能
- (void)setupRefresh {
    
    // 添加下拉刷新
    self.collectionView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [self.collectionView.mj_footer endRefreshing];
        [self.goods removeAllObjects];
        self.page = 0;
        self.parameters[@"page"] = @(self.page);
        [self loadGoodsDataWithParameters:self.parameters];
    }];
    
    // 添加上拉加载
    self.collectionView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        [self.collectionView.mj_header endRefreshing];
        self.page += 1;
        self.parameters[@"page"] = @(self.page);
        [self loadGoodsDataWithParameters:self.parameters];
    }];
}

//请求分类数据
- (void)loadCateData {

    [RequestManager fetchDataWithUrl:kCateList parameter:nil method:@"GET" compeleted:^(NSData *data) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSArray *cate = [KLCataList mj_objectArrayWithKeyValuesArray:dict[@"result"]];
        [self.cates addObjectsFromArray:cate];
        
        for (NSDictionary *dic in dict[@"result"]) {
            NSMutableArray *items = [KLSubCataList mj_objectArrayWithKeyValuesArray:dic[@"item"]];
            KLSubCataList *sub = [[KLSubCataList alloc] init];
            sub.basecategoryname = @"全部分类" ;
            sub.basecategorycode = nil;
            [items insertObject:sub atIndex:0];
            [self.subCates addObject:items];
        }
    } updateUI:^{
        
        [self.menu reloadData];
    }];
    
}

// 请求物品数据
- (void)loadGoodsDataWithParameters:(NSDictionary *)para {
//    [SVProgressHUD show];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10.0f;
    self.parameters = para.mutableCopy;

    [manager POST:kGoodsUrl parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
    
        NSDictionary *dictRoot = responseObject;
        for (NSDictionary *dict in dictRoot[@"result"]) {
            KLGood *goodModel = [KLGood goodModelWithDict:dict];
            [self.goods addObject:goodModel];
        }
       
        dispatch_async(dispatch_get_main_queue(), ^{

            // 结束刷新
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
            [UIView animateWithDuration:1.0 animations:^{
                
                self.hourGlass.alpha = 0;
            }];
            [self.collectionView reloadData];
            
        });

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        // 结束刷新
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
    
}

- (void)getMenuData {
    // 获取城市菜单
    self.citys = [NSMutableArray array];
    self.provinces = [NSMutableArray array];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"SearchLocations.plist" ofType:nil];
    NSDictionary *dictRoot = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    for (NSDictionary *dictArray in dictRoot[@"address"]) {
        
        [self.provinces addObject:dictArray[@"name"]];
        
        NSMutableArray *cityArray = [NSMutableArray array];
        for (NSDictionary *cityDict in dictArray[@"sub"]) {
            [cityArray addObject:cityDict[@"name"]];
        }
        [self.citys addObject:cityArray];
    }
    
    self.sorts = @[@"排序",@"最新发布", @"价格最低", @"价格最高"];
    [self.provinces insertObject:@"全国" atIndex:0];
    [self.citys insertObject:@[@"全国"] atIndex:0];
    
    KLCataList *cate = [[KLCataList alloc] init];
    cate.hotcategoryid = nil;
    cate.hotcategoryname = @"全部分类";
    [self.cates insertObject:cate atIndex:0];
    
    KLSubCataList *sub = [[KLSubCataList alloc] init];
    sub.basecategorycode = nil;
    sub.basecategoryname = @"全部分类" ;
    [self.subCates addObject:@[sub]];
    
    
}
#pragma mark - <UISearchBarDelegate>


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    KLSearchViewController *searchVc = [[KLSearchViewController alloc] init];
    searchVc.delegate = self;
    [self.navigationController pushViewController:searchVc animated:YES];

}


#pragma mark - <KLSelectedViewControllerDelegate>
- (void)passWord:(NSString *)word {
 
    [self.parameters removeAllObjects];
    self.parameters[@"page"] = @0;
    self.parameters[@"searchkeyword"] = word;
    [self loadGoodsDataWithParameters:self.parameters];
    [self.collectionView reloadData];
    [self.collectionView.mj_header beginRefreshing];
    
    self.searchBar.text = word;
    [self.menu reloadData];
}


#pragma mark - 设置导航栏

- (void)setupNavigation  {
    
    self.navigationItem.titleView = self.searchBar;
    UIBarButtonItem *changeLayout = [UIBarButtonItem itemWithImage:@"切换" highImage:nil target:self action:@selector(changeLayoutAction)];
    UIBarButtonItem *sort = [UIBarButtonItem itemWithImage:@"分类" highImage:nil target:self action:@selector(sortAction)];
    self.navigationItem.rightBarButtonItems = @[sort, changeLayout];
}
- (void)changeLayoutAction {
    
    self.isChanged = !self.isChanged;
    if (self.isChanged) {
        [self.collectionView setCollectionViewLayout:self.oneViewLayout animated:NO];
        [self.collectionView reloadData];
    }else {
        [self.collectionView setCollectionViewLayout:self.twoViewLayout animated:NO];
        [self.collectionView reloadData];
    }

}

- (void)sortAction {
    KLCateViewController *cataVc = [[KLCateViewController alloc] init];
    

    cataVc.cates = self.cates;
    __weak KLBuyViewController *weakSelf = self;
    cataVc.block = ^(NSInteger i) {
        [weakSelf.menu selectIndexPath:[LrdIndexPath indexPathWithColumn:0 row:i]];
        weakSelf.parameters[@"popcategorycodes"] = nil;
        weakSelf.parameters[@"hotcategoryid"] = [self.cates[i] hotcategoryid];
        [weakSelf loadGoodsDataWithParameters:weakSelf.parameters];
    };
    [self.navigationController pushViewController:cataVc animated:YES];

}

#pragma mark - <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.goods.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (!self.isChanged) {
        
        KLGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"goodsCell" forIndexPath:indexPath];

        if (self.goods.count != 0) {
            
            cell.goodModel = self.goods[indexPath.row];
        }
        return cell;
    }else {
        
        KLGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"otherGoods" forIndexPath:indexPath];
            cell.goodModel = self.goods[indexPath.row];
        return cell;
    }
    
    
}

#pragma mark - <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    YSLCommodityViewController *commodityVc = [[YSLCommodityViewController alloc] init];
    commodityVc.goodsID = [self.goods[indexPath.row] ID];
    
    [self.navigationController pushViewController:commodityVc animated:YES];
}






#pragma mark - <LrdSuperMenuDataSource>

// 有多少个column，默认为1列
- (NSInteger)numberOfColumnsInMenu:(LrdSuperMenu *)menu {
    return 4;
}

// 每个column有多少行
- (NSInteger)menu:(LrdSuperMenu *)menu numberOfRowsInColumn:(NSInteger)column{
 
    if (column == 0) {
        return self.cates.count;
    }else if(column == 1) {
        return self.provinces.count;
    }else if(column == 2){
        return self.sorts.count;
    }else {
        return 1;
    }
}

// 每个column中每行的title
- (NSString *)menu:(LrdSuperMenu *)menu titleForRowAtIndexPath:(LrdIndexPath *)indexPath {
    
    if (indexPath.column == 0) {
        
        if (!self.cates.count) return nil;
        return [self.cates[indexPath.row] hotcategoryname];
    }else if(indexPath.column == 1) {
        return self.provinces[indexPath.row];
    }else if(indexPath.column == 2){
        return self.sorts[indexPath.row];
    }else {
        return @"筛选";
    }
}


// 返回多少个子菜单
- (NSInteger)menu:(LrdSuperMenu *)menu numberOfItemsInRow:(NSInteger)row inColumn:(NSInteger)column {
    
    if (column == 0) {
        for (int i = 0; i < self.subCates.count; i++) {
            if (row == i) {
                NSArray *sub = self.subCates[i];
                return sub.count;
            }
        }
    }else if (column == 1) {
        for (int i = 0; i < self.provinces.count; i++) {
            
            if (row == i) {
                NSArray *cits = self.citys[i];
                return cits.count;
            }
        }
    }
    return 0;
}

- (NSString *)menu:(LrdSuperMenu *)menu titleForItemsInRowAtIndexPath:(LrdIndexPath *)indexPath {
    
    if (indexPath.column == 0) {
        
        if (!self.subCates.count) return nil;
        for (int i = 0; i < self.subCates.count; i++) {
            if (indexPath.row == i) {
                return [self.subCates[i][indexPath.item] basecategoryname];
            }
        }
        
    } else if (indexPath.column == 1) {
        
        for (int i = 0; i < self.citys.count; i++) {
            if (indexPath.row == i) {
                return self.citys[i][indexPath.item];
            }
        }
    }
    
    return nil;
    
}

- (NSString *)menu:(LrdSuperMenu *)menu detailTextForItemsInRowAtIndexPath:(LrdIndexPath *)indexPath {
    
    return nil;

}


#pragma mark - <LrdSuperMenuDelegate>
- (void)menu:(LrdSuperMenu *)menu didSelectRowAtIndexPath:(LrdIndexPath *)indexPath {
    
    [self.goods removeAllObjects];

     self.parameters[@"page"] = @0;
   
    if (indexPath.item >= 0) {
        
        
        if (indexPath.column == 0) {
 
            self.parameters[@"popcategorycodes"] = nil;
            self.parameters[@"hotcategoryid"] = nil;
            self.parameters[@"page"] = @0;
            
            NSLog(@"%@ ",[self.cates[indexPath.row] hotcategoryname]);
            
            NSLog(@"%@ ",[self.subCates[indexPath.row][indexPath.item] basecategoryname]);
            KLSubCataList *subCate = self.subCates[indexPath.row][indexPath.item];
            
            if (indexPath.row == 0) {
                self.parameters[@"popcategorycodes"] = nil;
                self.parameters[@"hotcategoryid"] = nil;

            }else if (!subCate.basecategorycode) {
                NSLog(@"%@", [self.cates[indexPath.row] hotcategoryid]);
                self.parameters[@"popcategorycodes"] = nil;
                self.parameters[@"hotcategoryid"] = [self.cates[indexPath.row] hotcategoryid];
            }else {
                
                self.parameters[@"popcategorycodes"] = @[subCate.basecategorycode];
                
            }
            [self loadGoodsDataWithParameters:self.parameters];
            [self.collectionView.mj_header beginRefreshing];
            
        }
        
        if (indexPath.column == 1) {
             NSLog(@"%@ ",self.citys[indexPath.row][indexPath.item]);
            [self.goods removeAllObjects];
            if (indexPath.row == 0) {
                self.parameters[@"province"] = nil;
                self.parameters[@"city"] = nil;
                self.parameters[@"area"] = nil;
            }else if (indexPath.row < 5) {
                if (indexPath.item == 0) {
                    self.parameters[@"province"] = nil;
                    self.parameters[@"area"] = nil;
                    self.parameters[@"city"] = self.citys[indexPath.row][indexPath.item];
                }else {
                    self.parameters[@"province"] = self.provinces[indexPath.row];
                    self.parameters[@"city"] = self.provinces[indexPath.row];
                    self.parameters[@"area"] = self.citys[indexPath.row][indexPath.item];
                }
            }else {
                    self.parameters[@"province"] = nil;
                    self.parameters[@"area"] = nil;
                    self.parameters[@"city"] = self.citys[indexPath.row][indexPath.item];
            }
           
            [self loadGoodsDataWithParameters:self.parameters];
            [self.collectionView.mj_header beginRefreshing];
        }
       
    }else {
    
        if (indexPath.column == 2) {
             NSLog(@"点击了%@",self.sorts[indexPath.row]);
            
            if (indexPath.row == 1) {
                self.parameters[@"sortword"] = @"updatetime-desc";
            }else if (indexPath.row == 2) {
                self.parameters[@"sortword"] = @"saleprice-asc";
            }else if (indexPath.row == 3) {
                self.parameters[@"sortword"] = @"saleprice-desc";
            }else {
                self.parameters[@"sortword"] = nil;
            }
      
            [self loadGoodsDataWithParameters:self.parameters];
            [self.collectionView.mj_header beginRefreshing];
        }
        
    }
    
   
}

- (void)meun:(LrdSuperMenu *)menu didSelectColumnAtIndex:(NSInteger)index {

    if (index == 3) {
        if (!self.selectedView.isHide) {
            self.selectedView.hidden = NO;
            [self.menu.backGroundView addSubview:self.selectedView];
            [UIView animateWithDuration:0.2 animations:^{
                self.selectedView.transform = CGAffineTransformMakeTranslation(0, kHeight * 0.4);
                
            }];
            
            
        }
    }else {
            self.selectedView.hidden = YES;
            
        }

    

}


#pragma mark - <KLSelectedViewDelegate>
- (void)selectedView:(KLSelectedView *)selectedView didClickedButton:(UIButton *)button WithBottomTextField:(UITextField *)bottomTextField highTextField:(UITextField *)highTextField {
    
    if (button.tag == kResetBtnTag) { // 点击重置按钮
        self.lastPriceLabel.backgroundColor = KLRGBColor(215, 255, 197);
        bottomTextField.text = nil;
        highTextField.text = nil;
        [self.parameters removeAllObjects];
        self.parameters[@"page"] = 0;
        [self.menu reloadData];
        [self.collectionView.mj_header beginRefreshing];
    }  else { // 点击确定按钮
        
        self.parameters[@"pricerange"] = [NSString stringWithFormat:@"%@-%@", bottomTextField.text, highTextField.text];
        [self loadGoodsDataWithParameters:self.parameters];
        [self.collectionView.mj_header beginRefreshing];

        [self.menu reloadData];
    }

}



- (void)selectedView:(KLSelectedView *)selectedView didClickedPriceLabel:(UIButton *)priceLabel WithPriceNum:(NSInteger)priceNum {

    self.lastPriceLabel.backgroundColor = KLRGBColor(215, 255, 197);
    priceLabel.backgroundColor = KLRGBColor(245, 213, 29);
    self.lastPriceLabel = priceLabel;
    self.parameters[@"pricerange"] = [NSString stringWithFormat:@"0.00-%.2ld", priceNum];
    
    [self loadGoodsDataWithParameters:self.parameters];
    [self.collectionView.mj_header beginRefreshing];
    [self.menu reloadData];
 
}

- (void)clickCancelBtn {
    
    [self.parameters removeAllObjects];
    self.parameters[@"page"] = 0;
    [self loadGoodsDataWithParameters:self.parameters];
    [self.collectionView.mj_header beginRefreshing];
    [self.menu reloadData];
}


@end
